package cloud.shyidong.core.controller;

import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.util.CosUtil;
import cloud.shyidong.core.util.ObjectUtils;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.transfer.Download;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Description TODO
 * @Author syd
 * @Date 2023/10/13
 */
@RestController
@RequestMapping("/cos")
@Slf4j
public class CosController {
    
    private String cosDownloadPath;
    
    private String bucketName;
    
    @Value("${cos.download.path}")
    public void setCosDownloadPath(String cosDownloadPath) {
        this.cosDownloadPath = cosDownloadPath;
    }
    
    @Value("${cos.bucket.name}")
    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
    
    @GetMapping("/{key}")
    public void get(@PathVariable String key, HttpServletResponse response) {
        File file = new File(cosDownloadPath + File.separator + key);
        if (!file.exists()) {
            try {
                GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
                Download download = CosUtil.getTransferManager().download(getObjectRequest, file);
                download.waitForCompletion();
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
                throw BusinessException.from("下载失败");
            }
        }
        response.setContentType("image/png");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data);
            inputStream.close();
            outputStream = response.getOutputStream();
            outputStream.write(data);
            outputStream.flush();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw BusinessException.from("下载失败");
        } finally {
            try {
                if (ObjectUtils.isNotNull(outputStream)) {
                    outputStream.close();
                }
                if (ObjectUtils.isNotNull(inputStream)) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
}
